<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Categoryrule;
use think\Cache;

class Categorydb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'category_id';

    protected $name = 'category';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id',
        'category_sign',
        'category_name',
        'audit_state',
        'level'
    ];

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    protected $autoWriteTimestamp = true;
    // 自动完成唯一标识
    protected function setCategorySignAttr($value)
    {
        if (! $value) {
            return md5(time() . round(1000, 9999));
        } else {
            return $value;
        }
    }
    // 自动完成英文缩写
    public function setInitailsAttr($initails)
    {
        return strtoupper($initails);
    }

    protected function setAuditStateAttr($value)
    {
        if ($value) {
            return $value;
        } else {
            if (SITE_ID) {
                // 获取分站信息
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                return 1;
            }
        }
    }
    // 自动完成层级
    public function setLevelAttr($value)
    {
        if ($value) {
            return $value;
        }
        if ($this->param['parent_sign'] == '0') {
            return 1;
        }
        $parent_level = $this->useGlobalScope(false)
            ->where('category_sign', $this->param['parent_sign'])
            ->field('level')
            ->find();
        return $parent_level['level'] + 1;
    }
    // 去除标题左右空格
    protected function setCategoryNameAttr($value)
    {
        return trim($value);
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeCategorySign($query, $category_sign)
    {
        $query->where('category_sign', 'IN', $category_sign);
    }

    public function scopeCategoryName($query, $category_name)
    {
        $query->where('category_name', 'like', '%' . $category_name . '%');
    }

    public function scopeInitails($query, $initails)
    {
        $query->where('initails', 'like', '%' . $initails . '%');
    }

    public function scopeAuditState($query, $audit_state)
    {
        $query->where('audit_state', $audit_state);
    }

    public function scopeLevel($query, $level)
    {
        $query->where('level', $level);
    }

    public function scopeApiOption($query, $api_option)
    {
        if(is_array($api_option)){
            $query->where('api_option','IN', $api_option);
        } else {
            $query->where('api_option', $api_option);
        }
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        /*$query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', 'null');
            } elseif ($this->param['site_id'] == - 1) {} else {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (! empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', 'null');
            }
        }*/
        if (isset($this->param['category_sign']) && $this->param['category_sign']) {
            $query->categorySign($this->param['category_sign']);
        }

        if (isset($this->param['audit_state']) && $this->param['audit_state']) {
            $query->auditState($this->param['audit_state']);
        }
        if (isset($this->param['category_name']) && $this->param['category_name']) {
            $query->categoryName($this->param['category_name']);
        }
        if (isset($this->param['initails']) && $this->param['initails']) {
            $query->initails($this->param['initails']);
            $this->search_flag = 1;
        }
        if (isset($this->param['parent_sign'])) {
            $query->parentSign($this->param['parent_sign']);
        }
        if (isset($this->param['level']) && $this->param['level']) {
            $query->level($this->param['level']);
        }
        if (isset($this->param['api_option']) && $this->param['api_option']) {
            $query->apiOption($this->param['api_option']);
        }
    }
    // 查询级别
    public function scopeParentSign($query, $parentSign)
    {
        if ($parentSign != 0 && is_numeric($parentSign)) {
            // 如果是数字 传入的是id
            $info = $this->where('category_id', $parentSign)
                ->find()
                ->toArray();
            $parentSign = $info['category_sign'];
        }
        $query->where('parent_sign', $parentSign);
    }
    // 查询排序最大值
    public function ajaxSortMax()
    {
        $max_sort = $this->cache($this->cache_name('category_max'), 86400, 'category')
            ->max('sort');
        return $max_sort;
    }

    public function ajaxAllSign($select_site_id)
    {
        if ($select_site_id) {
            $this->param['site_id'] = $select_site_id;
        }
        $data = $this->cache($this->cache_name('category_all_sign'), 86400, 'category')
            ->field('category_sign')
            ->select();
        if ($data) {
            return $data->toArray();
        } else {
            return [];
        }
    }
    // 查询列表
    public function ajaxSelect($parent_sign = '')
    {
        if ($parent_sign) {
            $this->param['parent_sign'] = $parent_sign;
        }
        $search_flag = 0;
        if (isset($this->param['category_name']) && $this->param['category_name']) {
            $search_flag = 1;
        }
        if (isset($this->param['initails']) && $this->param['initails']) {
            $search_flag = 1;
        }
        if ($search_flag == 0) {
            if (isset($this->param['parent_sign']) && ! empty($this->param['parent_sign'])) {
                $this->parentSign($this->param['parent_sign']);
            } else {
                $this->parentSign(0);
            }
        }
        $data = $this
            //->fetchSql(true)
            ->order('sort asc,category_id asc')
            ->group('category_sign')
            ->select();
        $count = $this->ajaxCount();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        $return['data'] = $data;
        $return['count'] = $count;
        return $return;
    }

    public function ajaxCount()
    {
        $count = $this
            ->count();
        return $count;
    }

    public function copy()
    {
        $data = $this->ajaxList();
        $add_data = array();
        if ($this->param['select_site_id'] == '') {
            $this->param['site_id'] = SITE_ID;
        } else {
            $this->param['site_id'] = $this->param['select_site_id'];
        }
        foreach ($data as $key => $val) {
            unset($val['category_id']);
            unset($val['create_time']);
            unset($val['site_id']);
            // unset($val['site_rate']);
            unset($val['api_option']);
            $val['site_id'] = $this->param['site_id'];
            $add_data[$key] = $val;
        }
        $this->ajaxDelete();
        $this->saveAll($add_data);
        return 'success';
    }

    public function ajaxList()
    {
        $data = $this->cache($this->cache_name('category_list'), 86400, 'category')
            ->order('sort asc,category_id asc')
            ->select();
        if ($data) {
            $data = $data->toArray();
            if (! isset($this->param['no_need_handle_data'])) {
                foreach ($data as $key => $val) {
                    $data[$key] = $this->handleData($val);
                }
            }
            return $data;
        } else {
            return array();
        }
    }

    public function ajaxTreeFind()
    {
        $data = $this->cache($this->cache_name('category_find'), 86400, 'category')
            ->find();
        if ($data) {
            $data = $data->toArray();
            $data['category_sign3'] = $data['category_sign'];
            if ($data['parent_sign'] == 0) {
                $data['category_sign2'] = $data['category_sign'];
                $data['category_sign1'] = $data['category_sign'];
            } else {
                $get_two = $this->aloneFind($data['parent_sign']);
                $data['category_sign2'] = $get_two['category_sign'];
                $data['category_sign1'] = $get_two['parent_sign'];
            }
        } else {
            $data = array();
        }
        return $data;
    }

    public function ajaxFind($category_sign)
    {
        if ($category_sign) {
            $this->param['category_sign'] = $category_sign;
        }
        $data = $this->master()
            ->where('category_sign', $this->param['category_sign'])
            ->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
            return $data;
        } else {
            return [];
        }
    }

    public function aloneFind($category_sign)
    {
        $data = $this->useGlobalScope(false)
            ->master()
            ->where('site_id', SITE_ID)
            ->where('category_sign', $category_sign)
            ->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
            return $data;
        } else {
            return [];
        }
    }

    public function ajaxUpdate()
    {
        $this->where('site_id', $this->param['site_id'])
            ->where('category_sign', $this->param['category_sign'])
            ->update($this->param);
        Cache::clear('category');
        return 'success';
    }

    public function ajaxSave()
    {
        $rule = new Categoryrule();
        $this->param['partner_id'] = PARTNER_ID;
        if (isset($this->param['site_id'])) {
            
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $this->param['site_id'] = null;
            } else {
                $this->param['site_id'] = $this->param['site_id'];
            }
        } else {
            if (! empty(SITE_ID)) {
                $this->param['site_id'] = SITE_ID;
            } else {
                $this->param['site_id'] = null;
            }
        }
        if (isset($this->param['category_sign']) && $this->param['category_sign'] != '') {
            if (! $rule->scene('edit')->check($this->param)) {
                return $rule->getError();
            }
        } else {
            if (! $rule->check($this->param)) {
                return $rule->getError();
            }
        }
        $site_id = $this->param['site_id'];
        unset($this->param['partner_id']);
        unset($this->param['site_id']);
        if (isset($this->param['category_sign']) && $this->param['category_sign'] != '') {
            $category_sign = $this->param['category_sign'];
            $get_last_save_data = $this->aloneFind($category_sign);
            unset($this->param['category_sign']);
            $this->save($this->param, [
                'category_sign' => $category_sign,
                'site_id' => $site_id
            ]);
            if (SITE_ID && $get_last_save_data['audit_state'] == - 1) {
                // 驳回之后修改内容
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    $this->save([
                        'audit_state' => 0
                    ], [
                        'site_id' => SITE_ID,
                        'category_sign' => $category_sign
                    ]);
                    $auditdb = new Auditdb();
                    $auditdb->param['audit_method'] = 1;
                    $auditdb->param['audit_type'] = 1;
                    $auditdb->param['site_id'] = SITE_ID;
                    $before_data = $this->param;
                    $auditdb->param['before_option'] = $before_data;
                    $auditdb->param['old_option'] = json_encode($before_data);
                    $after_data = $before_data;
                    $auditdb->param['after_option'] = $after_data;
                    $auditdb->param['audit_sign'] = $category_sign;
                    $audit_state = $auditdb->ajaxSave();
                }
            }
        } else {
            $add_data = $this->allowField(true)->save($this->param);
            // 保存属性
            $attr = new Attrdb();
            $attr->addCategoryAttr($this->category_sign);
            // 保存品牌
            $categoryBrand = new CategoryBranddb();
            $categoryBrand->addCategoryBrand($this->category_sign);
            if (SITE_ID) {
                // 新增 需要验证
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    $auditdb = new Auditdb();
                    $auditdb->param['audit_method'] = 1;
                    $auditdb->param['audit_type'] = 1;
                    $auditdb->param['site_id'] = SITE_ID;
                    $before_data = $this->param;
                    $auditdb->param['before_option'] = $before_data;
                    $auditdb->param['old_option'] = json_encode($before_data);
                    $after_data = $before_data;
                    $auditdb->param['after_option'] = $after_data;
                    $auditdb->param['audit_sign'] = $this->data['category_sign'];
                    $audit_state = $auditdb->ajaxSave();
                }
            }
        }
        Cache::clear('category');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['category_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('category_id', 'IN', $this->param['category_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('category_id', 'IN', $this->param['category_id']);
                });
            }
        }
        if (isset($this->param['category_sign'])) {
            $this->where('site_id', $this->param['site_id'])->delete();
        }
        Cache::clear('category');
        return 'success';
    }
    // 数据处理
    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'category_id':
                    $val['category_icon'] = "<span class='layui-icon layui-icon-right'></span>";
                    break;
                case 'category_picture':
                    $uploaddb = new Uploaddb();
                    if ($val['category_picture']) {
                        $val['category_picture_info'] = $uploaddb->getFind($val['category_picture']);
                    } else {
                        $val['category_picture_info'] = $uploaddb->getFindTemp();
                    }
                    break;
                default:
                    break;
            }
        }
        
        return $val;
    }
}